package com.zl.learning.thread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer> {

    private static final int THREAD_HOLD = 2;

    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小就计算
        boolean canCompute = (end - start) <= THREAD_HOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "work");
        } else {
            System.out.println(Thread.currentThread().getName()+"-分配工作");
            int middle = (start + end) / 2;
            System.out.println(Thread.currentThread().getName()+"-分配工作-left");
            CountTask left = new CountTask(start, middle);
            System.out.println(Thread.currentThread().getName()+"-分配工作-right");
            CountTask right = new CountTask(middle + 1, end);
            //执行子任务
            System.out.println(Thread.currentThread().getName()+"-分配工作-left-fork");
            left.fork();
            System.out.println(Thread.currentThread().getName()+"-分配工作-right-fork");
            right.fork();
//            invokeAll(left,right);
            //获取子任务结果
            System.out.println(Thread.currentThread().getName() + "-left join");
            int lResult = left.join();
            System.out.println(Thread.currentThread().getName() + "-right join");
            int rResult = right.join();
            sum = lResult + rResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        CountTask task = new CountTask(1, 100);
        Future<Integer> result = pool.submit(task);
        try {
            System.out.println(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
